import codecs

import openpyxl
import pandas as pd
import re
from openpyxl import load_workbook

import getPic


def buildScriptProject(url):
    # 读取Excel文件并转换为DataFrame对象
    excel_file = pd.ExcelFile(url)
    pic = {}
    # 获取所有工作表名称
    sheet_names = excel_file.sheet_names
    # 找到 Sheet2 的索引
    start_index = sheet_names.index('Sheet2')
    # 遍历工作表名称
    for sheet_name in sheet_names[start_index:]:
        print(f"工作表名称: {sheet_name}")
        df = pd.read_excel(url, sheet_name=sheet_name)
        pic = getPic.export_and_record_image_positions(url, './output/', sheet_name)
        print('pic:\t')
        print(pic)
        if sheet_name == 'Sheet2':
            sheet_name = 'script'
        # 获取第一列的数据，从第二行开始
        first_column = df.iloc[:, 0]
        print(f"first_column: " + first_column)
        # 去重并获取不同的元素
        unique_elements = first_column.dropna().unique()

        # 遍历 Excel 中的每一行和每一列

        escape_chars = ['{']
        escape_chars1 = ['\\[']
        escape_chars2 = ['【']
        escape_chars3 = ['\\)']
        # 遍历 DataFrame 中的每一列
        for column in df.columns:
            # 对每一列的值进行替换操作
            df[column] = df[column].apply(lambda x: re.sub('|'.join(escape_chars), '', str(x)))
            df[column] = df[column].apply(lambda x: re.sub('|'.join(escape_chars1), '', str(x)))
            df[column] = df[column].apply(lambda x: re.sub('|'.join(escape_chars2), '', str(x)))
            df[column] = df[column].apply(lambda x: re.sub('|'.join(escape_chars3), '', str(x)))
        pd.set_option('display.max_rows', None)  # 显示所有行
        pd.set_option('display.max_columns', None)  # 显示所有列
        pd.set_option('display.width', 1000)  # 设置显示宽度，根据需要调整
        # 打印DataFrame的内容
        print("读取的DataFrame:")
        print(df)
        print()

        # 获取DataFrame的列名
        print("列名:")
        print(df.columns)
        print()

        # 获取DataFrame的行数和列数
        print("行数和列数:")
        print(df.shape)
        print()

        # 打印不同元素的数量和数组内容
        print("不同元素的数量:", len(unique_elements))
        print("不同元素的数组:", unique_elements)

        elements = unique_elements

        # 定义字符串模板
        template = "define role{index} = Character('{element}', color='#c8c8ff' ,what_size=25)"

        # 生成字符串列表
        strings = [template.format(index=i + 1, element=element) for i, element in enumerate(elements)]

        roles = []
        position = "right"
        # 使用循环为每个元素生成一个角色
        for i in range(len(elements)):
            role = "role" + str(i + 1)
            roles.append(role)
        # 创建一个空字典来存储元素和角色的对应关系
        element_role_dict = {}

        # 使用循环将元素和角色对应起来，并将它们添加到字典中
        for i in range(len(elements)):
            element = elements[i]
            role = roles[i]
            element_role_dict[element] = role

        # 打印字典的内容
        print(element_role_dict)

        # 将字符串列表合并为一个字符串
        output_string = "\n".join(strings)
        with open('outputScript.txt', 'w', encoding='utf-8') as file:
            file.write("# 软件名称：基于案例研讨的AI医学教学科普软件的开发\n")
            file.write(
                "# 项目目的:本项目旨在开发一款用于医学知识辅助学习的解决方案，以解决PBL教学中存在的问题和医学科普工作中的挑战。\n")
            file.write("# 版权所有 (c) 2024 sdu_ipbl\n")
            file.write("# 本项目基于 MIT 许可证发布，详见 LICENSE 文件")
            file.write('\n')

        # 导出到txt文件
        outPath = './output/' + sheet_name + '.txt'

        with codecs.open(outPath, 'w', encoding='utf-8') as file:
            file.write(output_string)
            file.write('\n')

            # 开始编写正文部分
            if sheet_name == 'script':
                file.write('label start' + ':\n')
            else:
                file.write('label ' + sheet_name + ':\n')
            file.write('scene background\n')

            total_rows = df.shape[0]
            is_EndPic = False
            for index, row in df.iterrows():
                print("index" + str(index) + "row" + str(row))
                if index in pic:
                    print("input picture")
                    desired_string, _ = pic[index].split('.', 1)
                    file.write('show ' + desired_string + ' at top\n')
                    is_EndPic = True
                if row['分支'] != "nan" and index < total_rows:
                    file.write('menu:\n')
                    print(index)
                    while df.loc[int(index), '内容'] != "nan" and index < total_rows:
                        file.write('    "' + df.loc[int(index), '内容'] + '":\n')
                        file.write('        jump ' + df.loc[int(index), '分支'] + '\n')
                        index += 1
                        if index == total_rows:
                            break
                    if index == total_rows:
                        break

                else:
                    text = row['内容']  # 假设文本所在列名为'文本'
                    print(text)
                    print(element_role_dict)

                    character = row['角色']  # 假设人名所在列名为'人名'
                    print(character)
                    value = element_role_dict.get(character)
                    print(value)
                    if value:
                        picture = row['头像']
                        print(picture)
                        if picture != "nan":
                            print(f"show {picture} as {picture} at left")
                            file.write(f"show {picture} as {picture} at left")
                            file.write('\n')
                        print(f'{value} "{text}"')
                        file.write(f'{value} "{text}"')
                        if picture != "nan":
                            file.write('\n')
                            file.write(f'hide {picture}')
                        file.write('\n')
                    else:
                        print(element_role_dict.get('旁白'))
                        ele = element_role_dict.get('旁白')
                        file.write(ele + " \"" + text + "\"")
                        file.write('\n')
                if is_EndPic:
                    file.write('hide ' + desired_string + '\n')
                    is_EndPic = False

            # 开始编写结束部分
            file.write('return')
            file.write('\n')
            file.write('\n')
            file.write('\n')


if __name__ == '__main__':
    buildScriptProject("./Examples/wanDan.xlsx")
